package com.alks.function.controller.finance.salary;

import com.alibaba.fastjson.JSON;
import com.alks.common.aop.ApiRestController;
import com.alks.common.aop.WebLogger;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.entity.PcCuttingSalary;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.PcCuttingSalaryDto;
import com.alks.function.data.request.PcCuttingSalaryReq;
import com.alks.function.service.finance.salary.SalaryFileCreationService;
import io.jsonwebtoken.lang.Objects;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * @author:hxl
 * @create: 2024-06-26 17:11
 * @Description:
 */
@ApiRestController("/salaryFile")
@Api(tags = {"工厂-人事薪资作业-裁断件资作业-1"})
@Slf4j
public class PcCuttingSalaryController {
    private String redisId = "pc-cutting-detail";
    @Resource
    private SalaryFileCreationService salaryFileCreationService;

    @WebLogger
    @PostMapping("/getPcCuttingSalary")
    @ApiOperation("指令产量明细")
    public ResponseInfo getPcCuttingSalary(@RequestBody PcCuttingSalaryReq req) {
        return salaryFileCreationService.getPcCuttingSalary(req);
    }

    @WebLogger
    @PostMapping("/confirmSalary")
    @ApiOperation("结算确认、取消结算、财务备注")
    public ResponseInfo confirmSalary(@RequestBody PcCuttingSalaryDto req) {
        return salaryFileCreationService.confirmSalary(req);
    }

    @GetMapping("/returnCondition")
    @ApiOperation("部位返回")
    @WebLogger
    public ResponseInfo returnCondition() {
        return salaryFileCreationService.returnCondition();
    }

    @PostMapping("/getPcCuttingTotalWP")
    @ApiOperation(value = "派工总数、金额总数、总页数")
    @WebLogger
    public ResponseInfo getPcCuttingTotalWP(@RequestBody PcCuttingSalaryReq req) throws ExecutionException, InterruptedException {
        return salaryFileCreationService.getPcCuttingTotalWP(req);
    }


    @Autowired
    RedisService redisService;

    @PostMapping("/downPcCuttingSalaryDetail")
    @ApiOperation("导出")
    @WebLogger
    public void downPcCuttingSalaryDetail(HttpServletResponse response) throws IOException {
        if (Objects.isEmpty(redisService.scan(redisId))) throw new ServiceErrorException("请先进行查询");
        String string = redisService.get(redisId);
        List<PcCuttingSalary> list = JSON.parseArray(string, PcCuttingSalary.class);
        BigDecimal amtTotal = new BigDecimal(0);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (PcCuttingSalary salary : list) {
            try {
                Date date = salary.getDispatchDate();
                salary.setDispatchTime(dateFormat.format(date));
            }catch (Exception e){

            }
            BigDecimal o = salary.getAmt() == null ? new BigDecimal(0) : salary.getAmt();
            if (!Objects.isEmpty(salary)) amtTotal = amtTotal.add(o);
        }
        Map<String, BigDecimal> map = new HashMap<>();
        map.put("amtTotal", amtTotal);
        ExcelUtils.creatByTemplate(response, "结算明细模板.xls", "结算明细" + DateUtils.dateTimeNow(), list, map);
    }

    //冲裁计件汇总
    @PostMapping("/downloadCuttingCollect")
    @ApiOperation("导出月份汇总表")
    @WebLogger
    public void downloadCuttingCollect(HttpServletResponse response, @RequestParam String financeYymm) throws IOException {
        salaryFileCreationService.downloadCuttingCollect(response, financeYymm);
    }

    //导出员工汇总表
    @GetMapping("/workerDetail")
    @ApiOperation("员工汇总表")
    @WebLogger
    public ResponseInfo workerDetail() {
        Map<String,Object> map = new HashMap<>();
        if (Objects.isEmpty(redisService.scan(redisId))) throw new ServiceErrorException("请先进行查询");
        String string = redisService.get(redisId);
        List<PcCuttingSalary> list = JSON.parseArray(string, PcCuttingSalary.class);
        list = list.stream().filter(x->"Y".equals(x.getCfmFlag())).collect(Collectors.toList());
        Set<String> set = new HashSet<>();
        if (list.isEmpty()) return ResponseInfo.error("还未结算确认");
        list.forEach(x->set.add(x.getName()));
        for (String s : set) {
            Map<String,Object> xmap = new HashMap<>();
            BigDecimal total = new BigDecimal(0);
            List<PcCuttingSalary> collect = list.stream().filter(x -> x.getName().equals(s)).collect(Collectors.toList());
            for (PcCuttingSalary salary : collect) {
                total = total.add(salary.getQty());
            }
            PcCuttingSalary salary = collect.get(0);
            xmap.put("list",collect);
            xmap.put("total",total);
            xmap.put("name",salary.getName());
            xmap.put("deptName",salary.getDeptName());
            map.put(salary.getWorkerId(),xmap);
        }
        map.put("total",list.size());
        return ResponseInfo.ok(map);
    }

    @PostMapping({"/export/pdf"})
    @ApiOperation("导出pdf")
    @WebLogger
    public void exportPdf(HttpServletResponse response,@RequestBody PcCuttingSalaryReq req){
        salaryFileCreationService.exportPdf(response,req);
    }

}
